package com.testingedu.action.background;

import java.io.File;

import com.testingedu.jdbcDao.TIndexPictureDao;
import com.testingedu.model.FileInfo;
import com.testingedu.model.TIndexPicture;
import com.testingedu.utils.FileUpLoad;

public class TIndexPictureAction extends RequestContext {

	private static final long serialVersionUID = 4978208891392331213L;
	private TIndexPicture tIndexPicture;
	private static TIndexPictureDao tIndexPictureDao = new TIndexPictureDao();

	public void settIndexPicture(TIndexPicture tIndexPicture) {
		this.tIndexPicture = tIndexPicture;
	}

	public void _list() throws Exception {
		String url = request.getParameter("url");
		if ("info".equals(url)) {
			this.info(url);
		} else {
			createQueryResult();
			tIndexPictureDao.list(queryResult, tIndexPicture);
			request.setAttribute("queryResult", queryResult);
			request.getRequestDispatcher("/WEB-INF/admin/jsp/indexPicture/list.jsp")
					.forward(request, response);
		}
	}
	
	public void _update() throws Exception {
		tIndexPictureDao.update(tIndexPicture);
		response.sendRedirect("/testingedu2/admin/indexPicture/list");
	}
	
	public void _add() throws Exception {
		String url = request.getParameter("url");
		if ("jsp".equals(url)) {
			request.getRequestDispatcher("/WEB-INF/admin/jsp/indexPicture/add.jsp")
					.forward(request, response);
		} else {
			FileInfo uploadFile = new FileInfo();
			if(tIndexPicture == null) {
				tIndexPicture = new TIndexPicture();
			}
			try {
				String path = FileUpLoad.execute(request, response, servletContext, tIndexPicture, uploadFile, "upload"+File.separator +"head");
				tIndexPicture.setPath(path.replace("\\", "/"));
				tIndexPictureDao.add(tIndexPicture);
				response.sendRedirect("/testingedu2/admin/indexPicture/list");
			} catch (Exception e) {
				e.printStackTrace();
				request.getRequestDispatcher("/error/error.jsp")
				.forward(request, response);
			}
		}
	}
	
	public void _delete() throws Exception {
		tIndexPicture = tIndexPictureDao.info(tIndexPicture.getId());
		String path = servletContext.getRealPath(File.separator) + tIndexPicture.getPath();
		if('/' == File.separatorChar)
			path = path.replace("\\", File.separator);
		if('\\' == File.separatorChar)
			path = path.replace("/", File.separator);
		File dFile = new File(path);
		if(dFile.exists())
			dFile.delete();
		tIndexPictureDao.delete(tIndexPicture.getId());
		response.sendRedirect("/testingedu2/admin/indexPicture/list");
	}
	
	public static void main(String[] args) {
		String str = "/fdsffd/";
		System.out.println(str.replace("/", File.separator));
	}


	private void info(String url) throws Exception {
		tIndexPicture = tIndexPictureDao.info(tIndexPicture.getId());
		request.setAttribute("tIndexPicture", tIndexPicture);
		request.getRequestDispatcher(
				"/WEB-INF/admin/jsp/indexPicture/" + url + ".jsp").forward(
				request, response);
	}
}
